package com.crm.business.crm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.business.admin.mapper.AdminDeptMapper;
import com.crm.business.admin.mapper.AdminRoleMapper;
import com.crm.business.admin.mapper.AdminUserMapper;
import com.crm.business.admin.service.IAdminDeptService;
import com.crm.business.crm.mapper.BillCrmOrderPoolMapper;
import com.crm.business.crm.service.BillCrmOrderPoolService;
import com.crm.business.servlet.BaseServiceImpl;
import com.crm.business.utils.UserUtil;
import com.crm.common.admin.entity.PO.AdminDept;
import com.crm.common.admin.entity.PO.AdminRole;
import com.crm.common.admin.entity.PO.AdminUser;
import com.crm.common.constant.Constants;
import com.crm.common.crm.entity.BO.BillOrderPoolBO;
import com.crm.common.crm.entity.PO.BillCrmOrderPool;
import com.crm.common.crm.entity.PO.BillCrmStudentPool;
import com.crm.common.ka.core.common.Result;
import com.crm.common.ka.core.redis.Redis;
import com.crm.common.utils.StringUtils;

import com.crm.common.utils.spring.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class BillCrmOrderPoolServiceImpl extends BaseServiceImpl<BillCrmOrderPoolMapper, BillCrmOrderPool> implements BillCrmOrderPoolService {
    @Autowired
    private BillCrmOrderPoolMapper billCrmOrderPoolMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private AdminDeptMapper adminDeptMapper;
    @Autowired
    private Redis redis;


    @Override
    public IPage<BillCrmOrderPool> queryPageList(BillOrderPoolBO billOrderPoolBO) {
        IPage<BillCrmOrderPool> page = new Page<>(billOrderPoolBO.getPage(), billOrderPoolBO.getLimit());
        QueryWrapper<BillCrmOrderPool> queryWrapper = new QueryWrapper<>();
        IPage<BillCrmOrderPool> poolPage = billCrmOrderPoolMapper.selectPage(page, queryWrapper);
        List<BillCrmOrderPool> pageRecords = page.getRecords();
        List<BillCrmOrderPool> newpageRecords =new ArrayList<>();
        for (BillCrmOrderPool crmOrderPool : pageRecords) {
            if (!StringUtils.isEmpty(crmOrderPool.getAdminUserId())) {
                List<String> adminUserId = Arrays.asList(crmOrderPool.getAdminUserId().split(","));
                StringBuffer sb = new StringBuffer();
                for (String id : adminUserId) {
                    QueryWrapper<AdminUser> adminUserQueryWrapper = new QueryWrapper<>();
                    adminUserQueryWrapper.select("realname").eq("user_id", id);
                    AdminUser adminUser = adminUserMapper.selectOne(adminUserQueryWrapper);
                    String realname = adminUser.getRealname();
                    sb.append(realname).append(",");

                }
                crmOrderPool.setAdminUserName(sb.substring(0, sb.length() - 1));
            }
            if (!StringUtils.isEmpty(crmOrderPool.getMemberUserId())) {
                List<String> deptId = Arrays.asList(crmOrderPool.getMemberUserId().split(","));
                StringBuffer sb = new StringBuffer();
                for (String id : deptId) {
                    QueryWrapper<AdminRole> adminRoleQueryWrapper = new QueryWrapper<>();
                    adminRoleQueryWrapper.select("role_name").eq("role_id", id);
                    AdminRole adminRole = adminRoleMapper.selectOne(adminRoleQueryWrapper);
                    String name = adminRole.getRoleName();
                    sb.append(name).append(",");
                }
                crmOrderPool.setMemberUserName(sb.substring(0, sb.length() - 1));

            }
            if (!StringUtils.isEmpty(crmOrderPool.getMemberDeptId())) {
                List<String> deptId = Arrays.asList(crmOrderPool.getMemberDeptId().split(","));
                StringBuffer sb = new StringBuffer();
                for (String id : deptId) {
                    QueryWrapper<AdminDept> adminRoleQueryWrapper = new QueryWrapper<>();
                    adminRoleQueryWrapper.select("name").eq("dept_id", id);
                    AdminDept adminDept = adminDeptMapper.selectOne(adminRoleQueryWrapper);
                    String name = adminDept.getName();
                    sb.append(name).append(",");
                }
                crmOrderPool.setMemberDeptName(sb.substring(0, sb.length() - 1));
            }
            newpageRecords.add(crmOrderPool);

        }
        return poolPage.setRecords(newpageRecords);
    }

    @Override
    public Result<BillCrmOrderPool> queryById(Integer id) {
        BillCrmOrderPool crmOrderPool = billCrmOrderPoolMapper.selectById(id);
        return Result.ok(crmOrderPool);
    }

    @Override
    public Result<Map<String, Object>> update(BillCrmOrderPool billCrmOrderPool) {
        int i = billCrmOrderPoolMapper.updateById(billCrmOrderPool);
        if(i > 0){
            BillCrmOrderPool crmOrderPool = billCrmOrderPoolMapper.selectById(billCrmOrderPool.getOrderPoolId());
            redis.set(Constants.ORG_ORDER_POOL,crmOrderPool);
        }
        return Result.ok();
    }

    /**
     * 设置账单池权限
     * @param auth
     */
    @Override
    public void setOrderPoolAuth(JSONObject auth){
        QueryWrapper<BillCrmOrderPool> queryWrapper = new QueryWrapper<BillCrmOrderPool>();
        queryWrapper.eq("status", 1);
        BillCrmOrderPool orderPool = getBaseMapper().selectOne(queryWrapper);

        List<String> roleIds = Arrays.asList(orderPool.getMemberUserId().split(","));
        List<String> deptIds = Arrays.asList(orderPool.getMemberDeptId().split(","));

        List<Integer> allDeptIds = new ArrayList<>();
        for(String deptId : deptIds){
            allDeptIds.addAll(SpringUtils.getBean(IAdminDeptService.class).queryChildDept(Integer.valueOf(deptId)));
            allDeptIds.add(Integer.valueOf(deptId));
        }

        boolean deptAuth = allDeptIds.contains(UserUtil.getUser().getDeptId()) || UserUtil.isAdmin();

        if(deptAuth){
            List<Integer> roles = UserUtil.getUser().getRoles();
            List<String> roleIdsToStr = roles.stream().map(Object::toString).collect(Collectors.toList());
            JSONObject orderPoolAuth = new JSONObject();
            orderPoolAuth.put("index",true);
            orderPoolAuth.put("receive",true);
            boolean roleAuth = isContains(roleIds, roleIdsToStr) || UserUtil.isAdmin();
            if(roleAuth){
                orderPoolAuth.put("distribution",true);
            }
            auth.getJSONObject("crm").put("orderPool",orderPoolAuth);
        }
    }

    public static boolean isContains(List<String> oneList,List<String> otherList){
        for(String other : otherList){
            if(oneList.contains(other)){
                return true;
            }
        }
        return false;
    }

}
